﻿using System;
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Threading;
using nRoute.Components.Collections;
using nRoute.Components.Composition;
using nRoute.Utilities;

namespace nRoute.Components.Composition
{
    public abstract class ResourceLocatorBase
        : IResourceLocator
    {
        private volatile bool _isDisposed;
        private LazyDictionary<string, Object> _metadata;

#region IResourceLocator Members

        public IDictionary<string, Object> Metadata
        {
            get
            {
                if (_metadata == null) _metadata = new LazyDictionary<string, object>();
                return _metadata;
            }
        }

        Object IResourceLocator.GetResource(ITypeBuilder typeBuilder)
        {
            return GetInstance(typeBuilder);
        }

#endregion

#region Overridable

        protected abstract Object GetInstance(ITypeBuilder typeBuilder); 

        protected virtual void Dispose(bool disposing) 
        {
            if (disposing)
            {
                _isDisposed = true;
                if (_metadata != null) _metadata.Clear();
                _metadata = null;
            }
        }

#endregion

#region IDisposable Members

        public bool IsDisposed
        {
            get { return _isDisposed; }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

#endregion

        ~ResourceLocatorBase() { Dispose(false); }

    }
}
